<script setup>
import { ref, onMounted, computed } from 'vue'
import api from '../api/shoppingCar_api.js'
import { ElMessage, ElMessageBox } from 'element-plus'

// ---------------------- 表格数据 ----------------------
const tableData = ref([])
const total = ref(0)

// ---------------------- 分页对象 ----------------------
const searchObj = ref({
  current: 1,
  limit: 10,
  userId: '',
  productId: ''
})

// ---------------------- 加载购物车 ----------------------
const loadShoppingCar = async () => {
  try {
    const res = await api.page(searchObj.value)
    const cartWithTotal = (res.data || []).map(item => ({
      ...item,
      totalPrice: (Number(item.price) || 0) * (Number(item.quantity) || 0)
    }))
    tableData.value = cartWithTotal
    total.value = res.count || 0
  } catch (error) {
    console.error(error)
    tableData.value = []
    total.value = 0
    ElMessage.error('加载购物车失败')
  }
}

// ---------------------- 页面初始化 ----------------------
onMounted(async () => {
  await loadShoppingCar()
})

//----------------------- 查询 ----------------------
const handleSearch = async () => {
  searchObj.value.current = 1
  loadShoppingCar()
}

//----------------------- 分页 ----------------------
const handleCurrentChange = (val) => {
  searchObj.value.current = val
  loadShoppingCar()
}
const handleSizeChange = (val) => {
  searchObj.value.limit = val
  searchObj.value.current = 1
  loadShoppingCar()
}

//----------------------- 删除 ----------------------
const handleDelete = async (carId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个购物车项吗？', '提示', { type: 'warning' })
    await api.del(carId)
    ElMessage.success('删除成功')
    loadShoppingCar()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error('删除失败')
    }
  }
}

//----------------------- 编辑 ----------------------
const editDialogVisible = ref(false)
const editForm = ref({})

const handleEdit = (row) => {
  editForm.value = { ...row }
  editDialogVisible.value = true
}

const cancelEdit = () => {
  editForm.value = {}
  editDialogVisible.value = false
}

const submitEdit = async () => {
  if (editForm.value.price == null || editForm.value.quantity == null) {
    ElMessage.warning('请填写完整信息')
    return
  }
  try {
    const itemToEdit = {
      ...editForm.value,
      totalPrice: Number(editForm.value.price) * Number(editForm.value.quantity)
    }
    await api.edit(itemToEdit)
    ElMessage.success('修改成功')
    editDialogVisible.value = false
    loadShoppingCar()
  } catch (error) {
    console.error(error)
    ElMessage.error('修改失败')
  }
}

//----------------------- 新增 ----------------------
const addWinVisible = ref(false)
const newItem = ref({})

const showAddDialog = () => {
  newItem.value = { userId: '', productId: '', price: null, quantity: null, photo: '', description: '' }
  addWinVisible.value = true
}

const addCancel = () => {
  newItem.value = {}
  addWinVisible.value = false
}

const addCommit = async () => {
  if (!newItem.value.userId || !newItem.value.productId || newItem.value.price == null || newItem.value.quantity == null) {
    ElMessage.warning('请填写完整信息')
    return
  }
  try {
    const itemToAdd = {
      ...newItem.value,
      totalPrice: Number(newItem.value.price) * Number(newItem.value.quantity)
    }
    await api.add(itemToAdd)
    ElMessage.success('新增成功')
    await loadShoppingCar()
    addWinVisible.value = false
  } catch (error) {
    console.error(error)
    ElMessage.error('新增失败')
  }
}

//----------------------- 上传图片 ----------------------
const handleAddUploadSuccess = (response) => {
  newItem.value.photo = response.data
}
const handleEditUploadSuccess = (response) => {
  editForm.value.photo = response.data
}

//----------------------- 计算总价 ----------------------
const totalPrice = computed(() => {
  const price = Number(newItem.value.price) || 0
  const quantity = Number(newItem.value.quantity) || 0
  return price * quantity
})
</script>

<template>
  <div style="padding: 20px;">
    <h2>购物车列表</h2>

    <!-- 查询 -->
    <el-form :inline="true" :model="searchObj" style="margin-bottom: 10px;">
      <el-form-item label="用户ID">
        <el-input v-model="searchObj.userId" placeholder="请输入用户ID" clearable/>
      </el-form-item>
      <el-form-item label="商品ID">
        <el-input v-model="searchObj.productId" placeholder="请输入商品ID" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
<!--        <el-button type="success" @click="showAddDialog">新增</el-button>-->
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="carId" label="ID" width="100"/>
      <el-table-column prop="userId" label="用户ID" width="100"/>
      <el-table-column prop="username" label="用户名称" width="100"/>
      <el-table-column prop="productId" label="商品ID" width="100"/>
      <el-table-column prop="productName" label="商品名称" width="150"/>
      <el-table-column prop="price" label="单价" width="100"/>
      <el-table-column prop="quantity" label="数量" width="80"/>
      <el-table-column prop="totalPrice" label="总价" width="120"/>
      <el-table-column prop="carTime" label="加入时间" width="180"/>

      <!-- 新增商品描述列 -->
      <el-table-column prop="description" label="商品描述" width="200" />
      <el-table-column prop="photo" label="商品图片" width="120">
        <template #default="scope">
          <img v-if="scope.row.photo" :src="scope.row.photo" style="width: 100px; height: 100px"/>
        </template>
      </el-table-column>

      操作
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <!--          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>-->
          <el-button type="danger" size="small" @click="handleDelete(scope.row.carId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :total="total"
        :page-sizes="[10,20,30,40]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
    />

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑购物车项" width="500px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="用户ID">
          <el-input v-model="editForm.userId"/>
        </el-form-item>
        <el-form-item label="商品ID">
          <el-input v-model="editForm.productId"/>
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="editForm.price" type="number"/>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="editForm.quantity" type="number"/>
        </el-form-item>
        <!-- 新增商品描述字段 -->
        <el-form-item label="商品描述">
          <el-input
              v-model="editForm.description"
              type="textarea"
              :rows="3" />
        </el-form-item>
        <!--        <el-form-item label="商品图片">-->
        <!--          <el-upload-->
        <!--              class="avatar-uploader"-->
        <!--              action="/api/upload/file"-->
        <!--              :show-file-list="false"-->
        <!--              :on-success="handleEditUploadSuccess"-->
        <!--          >-->
        <!--            <img v-if="editForm.photo" :src="editForm.photo" style="width: 100px; height: 100px"/>-->
        <!--            <img v-else src="@/assets/shop.png" style="width:100px" />-->
        <!--          </el-upload>-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新增弹窗 -->
    <el-dialog v-model="addWinVisible" title="新增购物车项" width="500px">
      <el-form :model="newItem" label-width="100px">
        <el-form-item label="用户ID">
          <el-input v-model="newItem.userId"/>
        </el-form-item>
        <el-form-item label="商品ID">
          <el-input v-model="newItem.productId"/>
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="newItem.price" type="number"/>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="newItem.quantity" type="number"/>
        </el-form-item>
        <el-form-item label="总价">
          <el-input :value="totalPrice" disabled/>
        </el-form-item>
        <!-- 新增商品描述字段 -->
        <el-form-item label="商品描述">
          <el-input
              v-model="newItem.description"
              type="textarea"
              placeholder="请输入商品描述"
              :rows="3" />
        </el-form-item>
        <!--        <el-form-item label="商品图片">-->
        <!--          <el-upload-->
        <!--              class="avatar-uploader"-->
        <!--              action="/api/upload/file"-->
        <!--              :show-file-list="false"-->
        <!--              :on-success="handleAddUploadSuccess"-->
        <!--          >-->
        <!--            <img v-if="newItem.photo" :src="newItem.photo" style="width: 100px; height: 100px"/>-->
        <!--            <img v-else src="@/assets/shop.png" style="width:100px" />-->
        <!--          </el-upload>-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <el-button @click="addCancel">取消</el-button>
        <el-button type="primary" @click="addCommit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
h2 {
  color: rgba(244, 64, 64, 0.35);
  margin-bottom: 20px;
}
</style>
